﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using GestionEco;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace Ecosystème
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        #region variables game

        private GraphicsDeviceManager graphics;
        private SpriteBatch spriteBatch;
        private float[] tailleImages;
        private List<TypeEspece> listTypeEspece;
        private Form f;
        PanneauDeControle pannelControle;
        private frmGestionPlateau pannelGestionPlateau;
        private frmAjout pannelAjout;
        private int _vitesse;
        public int vitesse
        {
            get { return _vitesse; }
            set { _vitesse = value; }
        }
        bool etatThread = false;
        #endregion

        #region variables gestion du temps

        private float timer = 0.1F; 
        //const float TIMER = 0.1F;

        #endregion

        #region Variables gestion des controles
        private MouseState posSouris;
        private KeyboardState curState;
        private Vector2 positionDuClic;
        private float translationX = 0.0F;
        private float translationY = 0.0F;
        #endregion

        #region Variables de la 3D

            private readonly Vector2 scale = new Vector2(1.0f, 0.5f);
            private readonly Vector2 OrigineDeLaMap = new Vector2(-(TileCount * TileSize) / 2.0f, (TileCount * TileSize) / 2.0f);
            private const int TileCount = 5;
            private const int TileSize = 200;
            readonly float angleDeRotation = 0.7854f;
            private RenderTarget2D mapEn2D;
            private RenderTarget2D mapTransfo;

        #endregion

        public Game1()
        {
            tailleImages = new float[2];
            tailleImages[0] = 50;
            tailleImages[1] = 50;
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            graphics.PreferredBackBufferWidth = 800;
            graphics.PreferredBackBufferHeight = 600;
            this.IsMouseVisible = true;
            IntPtr ptr = this.Window.Handle;
            f = (System.Windows.Forms.Form)System.Windows.Forms.Control.FromHandle(ptr);
            f.FormBorderStyle = FormBorderStyle.None;
           

        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            #region Initialisation
            pannelControle = new PanneauDeControle();
            //pannelControle.AutoSizeMode = AutoSizeMode.GrowOnly;
            pannelControle.StartPosition = FormStartPosition.Manual;
            pannelControle.Location = new System.Drawing.Point(Screen.PrimaryScreen.Bounds.Width - 283 + (1366 - Screen.PrimaryScreen.Bounds.Width), 83);
            //pannelControle.Dock = DockStyle.Right;
            
            pannelControle.FormBorderStyle = FormBorderStyle.None;
            pannelControle.Show();
            pannelGestionPlateau = new frmGestionPlateau();
            //pannelGestionPlateau.AutoSizeMode = AutoSizeMode.GrowOnly;
            //pannelGestionPlateau.StartPosition = FormStartPosition.Manual;
            pannelGestionPlateau.FormBorderStyle = FormBorderStyle.None;
            //pannelGestionPlateau.Location = new System.Drawing.Point(5, 0);
            //pannelGestionPlateau.Dock = DockStyle.Top;
            pannelGestionPlateau.Quitter = false;
            pannelGestionPlateau.Reduire = false;
            pannelGestionPlateau.Play = false;
            pannelGestionPlateau.Show();
            listTypeEspece = new List<TypeEspece>();
            System.Drawing.Image img = System.Drawing.Image.FromFile(Content.RootDirectory + "/EtreVivants/Chevre.png");
            TypeEspece te = new TypeEspece("Chèvre", img);
            listTypeEspece.Add(te);
            img = System.Drawing.Image.FromFile(Content.RootDirectory + "/EtreVivants/Loup.png");
            te = new TypeEspece("Loup", img);
            listTypeEspece.Add(te);
            img = System.Drawing.Image.FromFile(Content.RootDirectory + "/EtreVivants/pigeon.png");
            te = new TypeEspece("Pigeon", img);
            listTypeEspece.Add(te);
            img = System.Drawing.Image.FromFile(Content.RootDirectory + "/EtreVivants/tulipe.png");
            te = new TypeEspece("Tulipe", img);
            listTypeEspece.Add(te);
            img = System.Drawing.Image.FromFile(Content.RootDirectory + "/EtreVivants/cactus.png");
            te = new TypeEspece("Cactus", img);
            listTypeEspece.Add(te);
            img = System.Drawing.Image.FromFile(Content.RootDirectory + "/EtreVivants/chat.png");
            te = new TypeEspece("Chat de gouttière", img);
            listTypeEspece.Add(te);
            img = System.Drawing.Image.FromFile(Content.RootDirectory + "/EtreVivants/chien.png");
            te = new TypeEspece("Chien sauvage", img);
            listTypeEspece.Add(te);
            img = System.Drawing.Image.FromFile(Content.RootDirectory + "/EtreVivants/chameau.png");
            te = new TypeEspece("Chameau", img);
            listTypeEspece.Add(te);
            pannelAjout = new frmAjout();
            //pannelAjout.AutoSizeMode = AutoSizeMode.GrowOnly;
            pannelAjout.StartPosition = FormStartPosition.Manual;
            pannelAjout.Location = new System.Drawing.Point(5, 83);
            //pannelAjout.Dock = DockStyle.Left;
            //pannelAjout.Dock = DockStyle.Bottom;
            pannelAjout.listtype = listTypeEspece;
            pannelAjout.Dock = DockStyle.Bottom;
            pannelAjout.Show();
            
            //f.AutoSizeMode = AutoSizeMode.GrowOnly;
            f.Dock = DockStyle.Bottom;
            f.Update();
           
            
            base.Initialize();
            #endregion
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            Traitements.initialisation(this.Content);
            Traitements.graphicDevice = this.graphics.GraphicsDevice;


            #region ConvertionImages
            convertionDesImages();
            #endregion

            #region Génération des maps pour 2D/3D
                mapEn2D = new RenderTarget2D(GraphicsDevice, TileCount * TileSize, TileCount * TileSize);
                mapTransfo = new RenderTarget2D(GraphicsDevice, 2 * (TileCount * TileSize), 2 * (TileCount * TileSize));
            #endregion

            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

       
        
        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
                this.Exit();


            // TODO: Add your update logic here
            #region Gestion du clavier et souris

            curState = Keyboard.GetState();
            posSouris = Mouse.GetState();
            //if (Traitements.lePlateau.EstEn3D)
            //{
            //    f.Width = 1084;
            //}
            //else
            //{
            //    f.Width = 800;
            //}


            if (curState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Enter))
            {
                if (Traitements.lePlateau.EstEn3D)
                {
                    Traitements.lePlateau.EstEn3D = false;
                }
                else
                {
                    Traitements.lePlateau.EstEn3D = true;
                }
                Thread.Sleep(60);

            }

            if (curState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Z))
            {
                //On zoome
                if(Traitements.taille[0] <11)
                Traitements.lePlateau.Zoom += 0.01F;
                else
                    Traitements.lePlateau.Zoom += 0.005F;

            }
            if (curState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.X))
            {
                // on dézoome
                //if (Traitements.lePlateau.Zoom > 0.1F)
                //{
                //    Traitements.lePlateau.Zoom -= 0.001F;
                //}
                if (Traitements.taille[0] == 5)
                {
                    if ((Traitements.lePlateau.Zoom > 0.41F))
                    {
                        Traitements.lePlateau.Zoom -= 0.01F;
                    }
                }
                if (Traitements.taille[0] == 6)
                {
                    if ((Traitements.lePlateau.Zoom > 0.35F))
                    {
                        Traitements.lePlateau.Zoom -= 0.01F;
                    }
                }
                if (Traitements.taille[0] == 7)
                {
                    if ((Traitements.lePlateau.Zoom > 0.295F))
                    {
                        Traitements.lePlateau.Zoom -= 0.01F;
                    }
                }
                if (Traitements.taille[0] == 8)
                {
                    if ((Traitements.lePlateau.Zoom > 0.26F))
                    {
                        Traitements.lePlateau.Zoom -= 0.01F;
                    }
                }
                if (Traitements.taille[0] == 9)
                {
                    if ((Traitements.lePlateau.Zoom > 0.234F))
                    {
                        Traitements.lePlateau.Zoom -= 0.01F;
                    }
                }
                if (Traitements.taille[0] == 10)
                {
                    if ((Traitements.lePlateau.Zoom > 0.21F))
                    {
                        Traitements.lePlateau.Zoom -= 0.01F;
                    }
                }
                if (Traitements.taille[0] >= 11)
                {
                    if ((Traitements.lePlateau.Zoom > 0.190F))
                    {
                        Traitements.lePlateau.Zoom -= 0.005F;
                    }
                }
                Thread.Sleep(10);

            }
            if (pannelGestionPlateau.Reduire)
            {
                pannelGestionPlateau.WindowState = FormWindowState.Minimized;
                if (pannelControle != null)
                    pannelControle.WindowState = FormWindowState.Minimized;
                f.WindowState = FormWindowState.Minimized;
                pannelAjout.WindowState = FormWindowState.Minimized;
                pannelGestionPlateau.Reduire = false;
            }
            if (f.WindowState == FormWindowState.Normal)
            {
                pannelGestionPlateau.WindowState = FormWindowState.Normal;
                if (pannelControle != null)
                    pannelControle.WindowState = FormWindowState.Normal;
                pannelAjout.WindowState = FormWindowState.Normal;
            }
            if (pannelGestionPlateau.Quitter)
            {
                
                if (pannelControle != null)
                    pannelControle.Close();
                pannelAjout.Close();
                this.Exit();
                pannelGestionPlateau.Close();
            }

            if (curState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Escape))
            {

                this.graphics.ToggleFullScreen();



            }
            if (curState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Right))
            {

                translationX -= 10.0F * Traitements.lePlateau.Zoom;

            }

            if (curState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Left))
            {
                // On se déplace vers la gauche
                if (translationX < 0F)
                {
                    if ((translationX + (10.0F * Traitements.lePlateau.Zoom)) < 0F)
                    {
                        translationX += 10.0F * Traitements.lePlateau.Zoom;
                    }
                    else
                    {
                        translationX = 0F;
                    }
                }

            }
            if (curState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Down))
            {

                translationY -= 10.0F * Traitements.lePlateau.Zoom;
            }
            if (curState.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Up))
            {
                // On se déplace vers le haut
                if (translationY < 0F)
                {
                    if ((translationY + (10.0F * Traitements.lePlateau.Zoom)) < 0F)
                    {
                        translationY += 10.0F * Traitements.lePlateau.Zoom;
                    }
                    else
                    {
                        translationY = 0F;
                    }
                }

            }
            if (posSouris.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
            {
                if (posSouris.X <= graphics.PreferredBackBufferWidth && posSouris.Y <= graphics.PreferredBackBufferHeight && posSouris.X >= 0 && posSouris.Y >= 0)
                {
                    positionDuClic = new Vector2((posSouris.X - translationX), (posSouris.Y - translationY));
                    positionDuClic = new Vector2(posSouris.X - translationX, posSouris.Y - translationY);

                    foreach (List<Case> C1 in Traitements.lePlateau.LesCases)
                    {

                        foreach (Case C2 in C1)
                        {
                            if ((positionDuClic.X > C2.Position.X) && (positionDuClic.X < (C2.Position.X + C2.TextureCase.Width * Traitements.lePlateau.Zoom)) && (positionDuClic.Y > C2.Position.Y) && (positionDuClic.Y < (C2.Position.Y + C2.TextureCase.Height * Traitements.lePlateau.Zoom)))
                            {
                                if (pannelAjout.terrain != null && !pannelGestionPlateau.Play)
                                {
                                    if (C2.Opacite == 200)
                                    {
                                        C2.Opacite = 255;
                                        pannelControle.Close();
                                        pannelControle = new PanneauDeControle();
                                        pannelControle.StartPosition = FormStartPosition.Manual;
                                        pannelControle.Location = new System.Drawing.Point(1083, 84);
                                        pannelControle.FormBorderStyle = FormBorderStyle.None;
                                        pannelControle.Show();
                                    }
                                    if (C2.ListEVCase.Count == 0)
                                    {
                                        //On sélectionne le terrain a ajouter pour cette case
                                        if (pannelAjout.terrain.Type == "Mer")
                                        {
                                            C2.TextureCase = Content.Load<Texture2D>("Mer");
                                            C2.Terrain = pannelAjout.terrain;
                                        }
                                        if (pannelAjout.terrain.Type == "Plaine")
                                        {
                                            C2.TextureCase = Content.Load<Texture2D>("Plaine");
                                            C2.Terrain = pannelAjout.terrain;
                                        }
                                        if (pannelAjout.terrain.Type == "Forêt")
                                        {
                                            C2.TextureCase = Content.Load<Texture2D>("Foret");
                                            C2.Terrain = pannelAjout.terrain;
                                        }
                                        if (pannelAjout.terrain.Type == "Montagne")
                                        {
                                            C2.TextureCase = Content.Load<Texture2D>("Montagne");
                                            C2.Terrain = pannelAjout.terrain;
                                        }
                                        if (pannelAjout.terrain.Type == "Désert")
                                        {
                                            C2.TextureCase = Content.Load<Texture2D>("Desert");
                                            C2.Terrain = pannelAjout.terrain;
                                        }
                                    }
                                    else
                                    {
                                        MessageBox.Show("Cette case contient des êtres vivants le type de terrain ne peut pas etre changé.");
                                    }
                                }
                                    if (pannelAjout.ImageEtre != null && !pannelGestionPlateau.Play)
                                    {
                                        if (C2.Opacite == 200)
                                        {
                                            C2.Opacite = 255;
                                            pannelControle.Close();
                                            pannelControle = new PanneauDeControle();
                                            pannelControle.StartPosition = FormStartPosition.Manual;
                                            pannelControle.Location = new System.Drawing.Point(1083, 84);
                                            pannelControle.FormBorderStyle = FormBorderStyle.None;
                                            pannelControle.Show();
                                        }
                                        Random rnd = new Random();
                                        //int randomNumber = rnd.Next(1, 7);
                                        Random rnd2 = new Random();
                                        int randomNumber2 = rnd.Next(1, 3);
                                        bool sexeAnimal = true;
                                        EtreVivant e = null;
                                        //On crée l'être vivant a insérer
                                        if (pannelAjout.nomEtre == "Tulipe")
                                        {
                                            // Ici il faut définir les caractéristique de la tullipe niveau soif
                                            e = new Tulipe(true, 5, 10, 1, 6, 10, 2, 2, System.Drawing.Image.FromFile(Application.StartupPath + @"\Content\EtreVivants\tulipe.png"));
                                        }
                                        if (pannelAjout.nomEtre == "Cactus")
                                        {
                                            e = new Cactus(true, 5, 10, 1, 6, 10, 2, 2, System.Drawing.Image.FromFile(Application.StartupPath + @"\Content\EtreVivants\cactus.png"));
                                        }
                                        if (pannelAjout.nomEtre == "Chameau")
                                        {
                                            // Paramètre à régler je vous laisse faire j'ai mis des paramètre par défaut pour le moment
                                            if (randomNumber2 == 1)
                                                sexeAnimal = true;
                                            else
                                                if (randomNumber2 == 2)
                                                    sexeAnimal = false;

                                        //int VieMax = 100 * rnd.Next(1, 7) * 10;
                                        //    int attaque = 2 * (rnd.Next(1, 7));
                                        //    int esquive = 2 * (rnd.Next(1, 7));
                                        //    int degats = 1 * (rnd.Next(1, 7));
                                        //    int vue = 5 * rnd.Next(1, 7);
                                        //    int regen = 15 * rnd.Next(1, 7);
                                        //    int faimMax = 10 * rnd.Next(1, 7);
                                        //    int soifMax = 10 * rnd.Next(1, 7);
                                            //int faimActuelle = this.faimMax;
                                            //int coeffFaim = unCoeffFaim;

                                            e = new Chameau(sexeAnimal, 100, 5, 8, 2, 6, 7, 200, 20, 200, 20, 6, 20, 5, 2, System.Drawing.Image.FromFile(Application.StartupPath + @"\Content\EtreVivants\chameau.png"));
                                        }
                                        if (pannelAjout.nomEtre == "Chat de gouttière")
                                        {
                                            // Paramètre à régler je vous laisse faire j'ai mis des paramètre par défaut pour le moment
                                            if (randomNumber2 == 1)
                                                sexeAnimal = true;
                                            else
                                                if (randomNumber2 == 2)
                                                    sexeAnimal = false;
                                            //int VieMax = 100 * rnd.Next(1, 7) * 10;
                                            //int attaque = 2 * (rnd.Next(1, 7));
                                            //int esquive = 2 * (rnd.Next(1, 7));
                                            //int degats = 1 * (rnd.Next(1, 7));
                                            //int vue = 5 * rnd.Next(1, 7);
                                            //int regen = 15 * rnd.Next(1, 7);
                                            //int faimMax = 10 * rnd.Next(1, 7);
                                            //int soifMax = 10 * rnd.Next(1, 7);
                                            //int faimActuelle = this.faimMax;
                                            //int coeffFaim = unCoeffFaim;

                                            e = new Chat(sexeAnimal, 100, 5, 8, 2, 6, 7, 200, 20, 200, 20, 6, 20, 5, 2, System.Drawing.Image.FromFile(Application.StartupPath + @"\Content\EtreVivants\chat.png"));
                                        }
                                        if (pannelAjout.nomEtre == "Chien sauvage")
                                        {
                                            // Paramètre à régler je vous laisse faire j'ai mis des paramètre par défaut pour le moment
                                            if (randomNumber2 == 1)
                                                sexeAnimal = true;
                                            else
                                                if (randomNumber2 == 2)
                                                    sexeAnimal = false;
                                            //int VieMax = 100 * rnd.Next(1, 7) * 10;
                                            //int attaque = 2 * (rnd.Next(1, 7));
                                            //int esquive = 2 * (rnd.Next(1, 7));
                                            //int degats = 1 * (rnd.Next(1, 7));
                                            //int vue = 5 * rnd.Next(1, 7);
                                            //int regen = 15 * rnd.Next(1, 7);
                                            //int faimMax = 10 * rnd.Next(1, 7);
                                            //int soifMax = 10 * rnd.Next(1, 7);
                                            //int faimActuelle = this.faimMax;
                                            //int coeffFaim = unCoeffFaim;

                                            e = new Chien(sexeAnimal, 100, 5, 8, 2, 6, 7, 200, 20, 200, 20, 6, 20, 5, 2, System.Drawing.Image.FromFile(Application.StartupPath + @"\Content\EtreVivants\chien.png"));
                                        }
                                        if (pannelAjout.nomEtre == "Loup")
                                        {
                                            // Paramètre à régler je vous laisse faire j'ai mis des paramètre par défaut pour le moment
                                            if (randomNumber2 == 1)
                                                sexeAnimal = true;
                                            else
                                                if (randomNumber2 == 2)
                                                    sexeAnimal = false;
                                            //int VieMax = 100 * rnd.Next(1, 7) * 10;
                                            //int attaque = 2 * (rnd.Next(1, 7));
                                            //int esquive = 2 * (rnd.Next(1, 7));
                                            //int degats = 1 * (rnd.Next(1, 7));
                                            //int vue = 5 * rnd.Next(1, 7);
                                            //int regen = 15 * rnd.Next(1, 7);
                                            //int faimMax = 10 * rnd.Next(1, 7);
                                            //int soifMax = 10 * rnd.Next(1, 7);
                                            //int faimActuelle = this.faimMax;
                                            //int coeffFaim = unCoeffFaim;

                                            e = new Loup(sexeAnimal, 100, 5, 8, 2, 6, 7, 200, 20, 200, 20, 6, 20, 5, 2, System.Drawing.Image.FromFile(Application.StartupPath + @"\Content\EtreVivants\loup.png"));
                                        }
                                        if (pannelAjout.nomEtre == "Pigeon")
                                        {
                                            // Paramètre à régler je vous laisse faire j'ai mis des paramètre par défaut pour le moment
                                            if (randomNumber2 == 1)
                                                sexeAnimal = true;
                                            else
                                                if (randomNumber2 == 2)
                                                    sexeAnimal = false;
                                            //int VieMax = 100 * rnd.Next(1, 7) * 10;
                                            //int attaque = 2 * (rnd.Next(1, 7));
                                            //int esquive = 2 * (rnd.Next(1, 7));
                                            //int degats = 1 * (rnd.Next(1, 7));
                                            //int vue = 5 * rnd.Next(1, 7);
                                            //int regen = 15 * rnd.Next(1, 7);
                                            //int faimMax = 10 * rnd.Next(1, 7);
                                            //int soifMax = 10 * rnd.Next(1, 7);
                                            //int faimActuelle = this.faimMax;
                                            //int coeffFaim = unCoeffFaim;

                                            e = new Pigeon(sexeAnimal, 100, 5, 8, 2, 6, 7, 200, 20, 200, 20, 6, 20, 5, 2, System.Drawing.Image.FromFile(Application.StartupPath + @"\Content\EtreVivants\pigeon.png"));
                                        }
                                        if (pannelAjout.nomEtre == "Chèvre")
                                        {
                                            // Paramètre à régler je vous laisse faire j'ai mis des paramètre par défaut pour le moment
                                            if (randomNumber2 == 1)
                                                sexeAnimal = true;
                                            else
                                                if (randomNumber2 == 2)
                                                    sexeAnimal = false;
                                            //int VieMax = 100 * rnd.Next(1, 7) * 10;
                                            //int attaque = 2 * (rnd.Next(1, 7));
                                            //int esquive = 2 * (rnd.Next(1, 7));
                                            //int degats = 1 * (rnd.Next(1, 7));
                                            //int vue = 5 * rnd.Next(1, 7);
                                            //int regen = 15 * rnd.Next(1, 7);
                                            //int faimMax = 10 * rnd.Next(1, 7);
                                            //int soifMax = 10 * rnd.Next(1, 7);
                                            //int faimActuelle = this.faimMax;
                                            //int coeffFaim = unCoeffFaim;

                                            e = new Chevre(sexeAnimal, 1, 5, 2, 2, 6, 7, 200, 20, 200, 20, 6, 20, 5, 2, System.Drawing.Image.FromFile(Application.StartupPath + @"\Content\EtreVivants\chevre.png"));
                                        }
                                       
                                        bool insertpossible = false;
                                        // On vérifie si la case contient un terrain et que cet être peut bien être mis dans ce terrain (On met pas un loup sur une mer !)
                                        if (e != null && C2.Terrain != null)
                                        {
                                            for (int k = 0; k < e.TypeTerrain.Count; k++)
                                            {
                                                if (e.TypeTerrain[k] == C2.Terrain.Type)
                                                    insertpossible = true;
                                            }
                                            if (!insertpossible)
                                                MessageBox.Show("Le type de terrain n'est pas adapté pour cet être vivant, vous devez insérer cet être sur un autre terrain.");
                                        }
                                        // Ajout a la liste de l'être vivant
                                        if (insertpossible)
                                        {
                                            C2.ListEVCase.Add(e);
                                            Traitements.laListeEcosysteme.Add(e);
                                        for (int t = 0; t < C2.ListEVCase.Count; t++)
                                            {
                                                System.Drawing.Image im = C2.ListEVCase[t].ImageEtre;
                                                //On resize l'image
                                                Bitmap img = new Bitmap(im, new Size(100, 100));
                                                using (MemoryStream s = new MemoryStream())
                                                {

                                                img.Save(s, System.Drawing.Imaging.ImageFormat.Png);
                                                    s.Seek(0, SeekOrigin.Begin);
                                                    // Ajout de l'image sur la texture de l'être vivant
                                                    C2.ListEVCase[t].Texture =Texture2D.FromStream(this.spriteBatch.GraphicsDevice, s);
                                                }
                                            }
                                        }
                                    }


                                    if (C2.Opacite == 255 && pannelAjout.terrain == null && pannelAjout.ImageEtre == null)
                                    {
                                        pannelControle.LaCaseSelectionnee = C2;
                                        pannelControle.chargementDuPanneau();
                                        C2.Opacite = 200;
                                    }
                                }
                                else
                                {
                                    C2.Opacite = 255;
                                }
                              
                            }
                        }
                    Thread.Sleep(50);
                    }
                }
            
                if (posSouris.RightButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
                {
                    if (posSouris.X <= graphics.PreferredBackBufferWidth && posSouris.Y <= graphics.PreferredBackBufferHeight && posSouris.X >= 0 && posSouris.Y >= 0)
                    {
                        positionDuClic = new Vector2(posSouris.X - translationX, posSouris.Y - translationY);

                        foreach (List<Case> C1 in Traitements.lePlateau.LesCases)
                        {

                            foreach (Case C2 in C1)
                            {
                                if ((positionDuClic.X > C2.Position.X) && (positionDuClic.X < (C2.Position.X + C2.TextureCase.Width * Traitements.lePlateau.Zoom)) && (positionDuClic.Y > C2.Position.Y) && (positionDuClic.Y < (C2.Position.Y + C2.TextureCase.Height * Traitements.lePlateau.Zoom)))
                                {
                                    if (C2.Opacite == 200)
                                    {
                                        C2.Opacite = 255;
                                        pannelControle.Close();
                                        pannelControle = new PanneauDeControle();
                                        pannelControle.StartPosition = FormStartPosition.Manual;
                                        pannelControle.Location = new System.Drawing.Point(Screen.PrimaryScreen.Bounds.Width - 283 + (1366 - Screen.PrimaryScreen.Bounds.Width), 83);
                                        pannelControle.FormBorderStyle = FormBorderStyle.None;
                                        pannelControle.Show();
                                    }
                                }
                            }
                        }
                    }
                    float time = 0.5F;
                    float elapsedTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
                    if (time <= 0)
                    {
                        // Hanlde the blink here
                        time = 0.5f; // Reset timer
                    }

                }
            #endregion

                #region Correction translation
                if (!Traitements.lePlateau.EstEn3D)
                {
                    if (translationX < ((Traitements.lePlateau.LesCases[0][0].TextureCase.Width * (Traitements.lePlateau.LesCases.Count - (2 / Traitements.lePlateau.Zoom)) * Traitements.lePlateau.Zoom) * -1))
                    {

                        translationX = (Traitements.lePlateau.LesCases[0][0].TextureCase.Width * (Traitements.lePlateau.LesCases.Count - (2 / Traitements.lePlateau.Zoom)) * Traitements.lePlateau.Zoom) * -1;

                    }
                    if (translationY < (Traitements.lePlateau.LesCases[0][0].TextureCase.Height * (Traitements.lePlateau.LesCases.Count - (1.5F / Traitements.lePlateau.Zoom)) * Traitements.lePlateau.Zoom) * -1)
                    {

                        translationY = (Traitements.lePlateau.LesCases[0][0].TextureCase.Height * (Traitements.lePlateau.LesCases.Count - (1.5F / Traitements.lePlateau.Zoom)) * Traitements.lePlateau.Zoom) * -1;
                    }
                }
                else
                {
                    if (translationX < ((Traitements.lePlateau.LesCases[0][0].TextureCase.Width * (Traitements.lePlateau.LesCases.Count - (2.5F / Traitements.lePlateau.Zoom)) * Traitements.lePlateau.Zoom) * -1))
                    {

                        translationX = (Traitements.lePlateau.LesCases[0][0].TextureCase.Width * (Traitements.lePlateau.LesCases.Count - (2.5F / Traitements.lePlateau.Zoom)) * Traitements.lePlateau.Zoom) * -1;

                    }
                    if (translationY < (Traitements.lePlateau.LesCases[0][0].TextureCase.Width * (Traitements.lePlateau.LesCases.Count - (2.5F / Traitements.lePlateau.Zoom)) * Traitements.lePlateau.Zoom) * -1)
                    {

                        translationY = (Traitements.lePlateau.LesCases[0][0].TextureCase.Width * (Traitements.lePlateau.LesCases.Count - (2.5F / Traitements.lePlateau.Zoom)) * Traitements.lePlateau.Zoom) * -1;
                    }
                }
                #endregion

                #region actions des etre vivants


                if (pannelGestionPlateau.Play)
                {
                    List<string> actionDetail = new List<string>();
                    //_vitesse = pannelGestionPlateau.Time;
                    float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
                    timer -= elapsed;
                    if (timer < 0)
                    {
                        if ((Traitements.laListeEcosysteme.Count != 0) && (Traitements.start))
                        {
                            Traitements.actionEtreVivant(actionDetail);
                        }
                        timer = pannelGestionPlateau.Time;
                    }
                   
                    //Fin du tour

                    pannelGestionPlateau.actionDialog = actionDetail;

                  

                }
              
               
                #endregion

                base.Update(gameTime);

            }
        

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
             GraphicsDevice.Clear(Microsoft.Xna.Framework.Color.White);
             if (Traitements.lePlateau.EstEn3D)
             {
                 GraphicsDevice.SetRenderTarget(mapEn2D);
             }
             spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, RasterizerState.CullNone, null, matriceDeTranslation(GraphicsDevice));

             // TODO: Add your drawing code here
             #region Dessin des Etre et cases
                 //Les cases sont dessinées

                 float hauteur = 0;
                 float largeur = 0;

                 System.Console.WriteLine(positionDuClic.X.ToString() + " : " + positionDuClic.Y.ToString());
                
	             foreach (List<Case> C1 in Traitements.lePlateau.LesCases)
	             {
	                 hauteur = 0;
	                 foreach (Case C2 in C1)
	                 {
	                     
	                     //Création des coordonnées de la case
	                     C2.Position = new Vector2(largeur, hauteur);
                         
	                     //On dessine les cases
                         spriteBatch.Draw(C2.TextureCase, C2.Position, Microsoft.Xna.Framework.Color.FromNonPremultiplied(255, 255, 255, C2.Opacite));
                         hauteur += C2.TextureCase.Height;
	                 }
                     largeur += C1.ElementAt(0).TextureCase.Width;
	             }

             spriteBatch.End();
            //Les etre vivants sont dessinés
            float rad = -0.424999744F;
            spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, SamplerState.LinearClamp, DepthStencilState.None, RasterizerState.CullNone, null, matriceDeTranslation(GraphicsDevice));
            float interieurCaseX = 0;
            float interieurCaseY = 0;
            List<String> dejaDessine= new List<String>();

            foreach (List<Case> C3 in Traitements.lePlateau.LesCases)
            {

                foreach (Case C4 in C3)
                {
                    int compteImageCase = 0;
                    foreach (EtreVivant ev in C4.ListEVCase)
                    {

                        if (dejaDessine.IndexOf(ev.GetType().ToString()) == -1)
                        {
                            if (compteImageCase == 0)
                                spriteBatch.Draw(ev.Texture, new Vector2(C4.Position.X + 0, C4.Position.Y + 0), null, Microsoft.Xna.Framework.Color.FromNonPremultiplied(255, 255, 255, 255), rad, new Vector2(-0, -60), 0.8F, SpriteEffects.None, 0);
                            if (compteImageCase == 1)
                            {
                                spriteBatch.Draw(ev.Texture, new Vector2(C4.Position.X + 0, C4.Position.Y + 100), null, Microsoft.Xna.Framework.Color.FromNonPremultiplied(255, 255, 255, 255), rad, new Vector2(-0, -60), 0.8F, SpriteEffects.None, 0);
                            }
                            if (compteImageCase == 2)
                                spriteBatch.Draw(ev.Texture, new Vector2(C4.Position.X + 100, C4.Position.Y + 0), null, Microsoft.Xna.Framework.Color.FromNonPremultiplied(255, 255, 255, 255), rad, new Vector2(-0, -60), 0.8F, SpriteEffects.None, 0);
                            if (compteImageCase == 3)
                                spriteBatch.Draw(ev.Texture, new Vector2(C4.Position.X + 100, C4.Position.Y + 100), null, Microsoft.Xna.Framework.Color.FromNonPremultiplied(255, 255, 255, 255), rad, new Vector2(-0, -60), 0.8F, SpriteEffects.None, 0);
                            if (compteImageCase == 4)
                                spriteBatch.Draw(ev.Texture, new Vector2(C4.Position.X + 200, C4.Position.Y + 0), null, Microsoft.Xna.Framework.Color.FromNonPremultiplied(255, 255, 255, 255), rad, new Vector2(-0, -110), 0.8F, SpriteEffects.None, 0);
                            if (compteImageCase == 5)
                                spriteBatch.Draw(ev.Texture, new Vector2(C4.Position.X + 200, C4.Position.Y + 100), null, Microsoft.Xna.Framework.Color.FromNonPremultiplied(255, 255, 255, 255), rad, new Vector2(-0, -110), 0.8F, SpriteEffects.None, 0);
                            if (compteImageCase == 6)
                                spriteBatch.Draw(ev.Texture, new Vector2(C4.Position.X + 0, C4.Position.Y + 200), null, Microsoft.Xna.Framework.Color.FromNonPremultiplied(255, 255, 255, 255), rad, new Vector2(-0, -110), 0.8F, SpriteEffects.None, 0);
                            if (compteImageCase == 7)
                                spriteBatch.Draw(ev.Texture, new Vector2(C4.Position.X + 100, C4.Position.Y + 200), null, Microsoft.Xna.Framework.Color.FromNonPremultiplied(255, 255, 255, 255), rad, new Vector2(-0, -110), 0.8F, SpriteEffects.None, 0);
                            if (compteImageCase == 8)
                                spriteBatch.Draw(ev.Texture, new Vector2(C4.Position.X + 200, C4.Position.Y + 200), null, Microsoft.Xna.Framework.Color.FromNonPremultiplied(255, 255, 255, 255), rad, new Vector2(-0, -110), 0.8F, SpriteEffects.None, 0);
                            //spriteBatch.Draw(ev.Texture, new Vector2(C4.Position.X + interieurCaseX, C4.Position.Y + interieurCaseY), null, Microsoft.Xna.Framework.Color.White, rad, new Vector2(-0, -60), 0.8F, SpriteEffects.None, 0);
                            interieurCaseX += ev.Texture.Width;
                            interieurCaseY += ev.Texture.Height;
                            dejaDessine.Add(ev.GetType().ToString());
                            if (compteImageCase < 8)
                                compteImageCase++;
                        }

                        ev.CasePosition = C4;
                    }

                    interieurCaseX = 0;
                    interieurCaseY = 0;
                    dejaDessine.Clear();
                    //Redimentionnement par rapport a la valeur du zoom
                    C4.Position = C4.Position * Traitements.lePlateau.Zoom;
                }

            }
                 #endregion
            

            spriteBatch.End();

            #region passage En 3D
            if (Traitements.lePlateau.EstEn3D)
            {
                Vector2 vect3D;
                GraphicsDevice.SetRenderTarget(mapTransfo);
                GraphicsDevice.Clear(Microsoft.Xna.Framework.Color.White);

                spriteBatch.Begin();
                spriteBatch.Draw(mapEn2D, new Vector2(0, 400), null, Microsoft.Xna.Framework.Color.White, angleDeRotation, OrigineDeLaMap, 0.9F, SpriteEffects.None, 0);
                spriteBatch.End();

                GraphicsDevice.SetRenderTarget(null);
                GraphicsDevice.Clear(Microsoft.Xna.Framework.Color.White);

                spriteBatch.Begin();
                vect3D = new Vector2(0.63F, 0.25F);
                spriteBatch.Draw(mapTransfo, Vector2.Zero, null, Microsoft.Xna.Framework.Color.White, 0, Vector2.Zero, vect3D, SpriteEffects.None, 0);
                spriteBatch.End();
            }
            #endregion


            Traitements.start = true;
            base.Draw(gameTime);
        }

        public Matrix matriceDeTranslation(GraphicsDevice graphicsDevice)
        {
            float Tx = translationX;
            float Ty = translationY;
            Matrix translateToOrigin = Matrix.CreateTranslation(0, 0, 0);

            // On crée le zoom 
            Matrix zoomMatrix = Matrix.CreateScale(Traitements.lePlateau.Zoom, Traitements.lePlateau.Zoom, 0);
            // On crée la translation
            Microsoft.Xna.Framework.Matrix translateBackToPosition = Microsoft.Xna.Framework.Matrix.CreateTranslation(Tx, Ty, 0);

            //On redimentionne en fonction des valeur
            Microsoft.Xna.Framework.Matrix compositeMatrix = zoomMatrix * translateBackToPosition * translateToOrigin;

            // On renvoie la transformation
            return compositeMatrix;
        }

        public void convertionDesImages()
        {
            foreach (List<Case> C1 in Traitements.lePlateau.LesCases)
            {
                foreach (Case C2 in C1)
                {
                    System.Drawing.Image im = C2.ImageCase;
                    //On resize l'image
                    Bitmap img = new Bitmap(im, 400, 400);
                    using (MemoryStream s = new MemoryStream())
                    {

                        img.Save(s, System.Drawing.Imaging.ImageFormat.Png);
                        s.Seek(0, SeekOrigin.Begin);
                        // Ajout de l'image sur la texture de l'être vivant
                        C2.TextureCase = Texture2D.FromStream(this.spriteBatch.GraphicsDevice, s);
                    }
                }
            }
            foreach (EtreVivant e in Traitements.laListeEcosysteme)
            {
                System.Drawing.Image im = e.ImageEtre;
                //On resize l'image
                Bitmap img = new Bitmap(im, new Size(100, 100));
                using (MemoryStream s = new MemoryStream())
                {

                    img.Save(s, System.Drawing.Imaging.ImageFormat.Png);
                    s.Seek(0, SeekOrigin.Begin);
                    // Ajout de l'image sur la texture de l'être vivant
                    e.Texture = Texture2D.FromStream(this.spriteBatch.GraphicsDevice, s);
                }
            }
        }

    }
}
